package com.tan.lbs.dao.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Xml;

import com.tan.lbs.dao.QuestDAO;
import com.tan.lbs.entity.NPC;
import com.tan.lbs.entity.Quest;
import com.tan.lbs.util.Constants;
import com.tan.lbs.util.SQLiteDatabaseHelper;

public class QuestDAOImpl implements QuestDAO {

	private Context context;

	public QuestDAOImpl(Context context) {
		this.context = context;
	}

	@Override
	public List<Quest> retreiveQuests(String gameID) {
		List<Quest> quests = null;
		Quest quest = null;
		SQLiteDatabase db = null;
		try {
			XmlPullParser parser = Xml.newPullParser();
			parser.setInput(
					context.getResources().getAssets()
							.open("gameFiles/" + gameID + "/quest.xml"),
					"UTF-8");

			int event = parser.getEventType();
			while (event != XmlPullParser.END_DOCUMENT) {
				switch (event) {
				case XmlPullParser.START_DOCUMENT:
					quests = new ArrayList<Quest>();
					break;
				case XmlPullParser.START_TAG:
					if ("quest".equals(parser.getName())) {
						quest = new Quest();
					}
					if (quest != null) {
						if ("questID".equals(parser.getName())) {
							quest.setQuestID(parser.nextText());
						} else if ("iconID".equals(parser.getName())) {
							quest.setIconID(parser.nextText());
						} else if ("completeText".equals(parser.getName())) {
							quest.setCompleteText(parser.nextText());
						} else if ("lat".equals(parser.getName())) {
							quest.setLat(Float.valueOf(parser.nextText()));
						} else if ("lng".equals(parser.getName())) {
							quest.setLng(Float.valueOf(parser.nextText()));
						} else if ("questOrder".equals(parser.getName())) {
							quest.setQuestOrder(Integer.valueOf(parser
									.nextText()));
						} else if ("dialogID".equals(parser.getName())) {
							quest.setStartText(parser.nextText());
						} else if ("title".equals(parser.getName())) {
							quest.setTitle(parser.nextText());
						}
					}
					break;
				case XmlPullParser.END_TAG:
					if ("quest".equals(parser.getName())) {
						SQLiteDatabaseHelper dbHelper = new SQLiteDatabaseHelper(
								context, Constants.LOCAL_DB_NAME);
						db = dbHelper.getReadableDatabase();

						Cursor cursor = db.query("quest", new String[] {
								"questID", "status" }, "questID=?",
								new String[] { quest.getQuestID() }, null,
								null, null);
						if (cursor.moveToNext()) {
							quest.setStatus(cursor.getString(cursor
									.getColumnIndex("status")));
						}
						quests.add(quest);
						quest = null;
					}
					break;
				}
				event = parser.next();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (db != null) {
				db.close();
			}
		}
		return quests;
	}

	@Override
	public void updateQuestStatus(String questID, String status) {
		SQLiteDatabaseHelper dbHelper = new SQLiteDatabaseHelper(context,
				Constants.LOCAL_DB_NAME);
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put("status", status);
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		if (status.equals(Quest.START_STATUS)) {
			values.put("startDateTime", dateFormat.format(date));
		} else if (status.equals(Quest.COMPLETE_STATUS)) {
			Cursor cursor = db.query("quest", new String[] { "questID",
					"startDateTime" }, "questID=?", new String[] { questID }, null,
					null, null);
			String start = "";
			if (cursor.moveToNext()) {
				start = cursor.getString(cursor.getColumnIndex("startDateTime"));
			}
			Date startDate = null;
			try {
				startDate  = dateFormat.parse(start);
			} catch (ParseException e) {
				e.printStackTrace();
			} 
			int secs = 0; int mins = 0; int hours = 0;
			if(startDate!=null) {
				Date endDate = date;
				secs = (int)((endDate.getTime() - startDate.getTime()) / 1000);
				hours = secs / 3600;    
				secs = secs % 3600;
				mins = secs / 60;
				secs = secs % 60;
			}
			String duration = String.valueOf(hours)+":"+String.valueOf(mins)+":"+String.valueOf(secs);
			values.put("duration", duration);
		}
		db.update("quest", values, "questID=?", new String[] { questID });
		db.close();

	}

	@Override
	public Quest readQuest(String questID, String gameID) {
		Quest quest = null;
		SQLiteDatabase db = null;
		try {
			XmlPullParser parser = Xml.newPullParser();
			parser.setInput(
					context.getResources().getAssets()
							.open("gameFiles/" + gameID + "/quest.xml"),
					"UTF-8");

			int event = parser.getEventType();
			String searchID;
			boolean found = false;
			while (event != XmlPullParser.END_DOCUMENT) {
				if (event == XmlPullParser.START_TAG) {
					if ("questID".equals(parser.getName())) {
						searchID = parser.nextText();
						if (searchID.equals(questID)) {
							quest = new Quest();
							quest.setQuestID(questID);
							found = true;
						}
					} else if ("title".equals(parser.getName()) && found) {
						quest.setTitle(parser.nextText());
					} else if ("iconID".equals(parser.getName()) && found) {
						quest.setIconID(parser.nextText());
					} else if ("startText".equals(parser.getName()) && found) {
						quest.setStartText(parser.nextText());
					} else if ("completeText".equals(parser.getName()) && found) {
						quest.setCompleteText(parser.nextText());
					} 
				} else if (event == XmlPullParser.END_TAG && found
						&& "quest".equals(parser.getName())) {
					SQLiteDatabaseHelper dbHelper = new SQLiteDatabaseHelper(
							context, Constants.LOCAL_DB_NAME);
					db = dbHelper.getReadableDatabase();

					Cursor cursor = db.query("quest", new String[] { "questID","duration",
							"status" }, "questID=?",
							new String[] { quest.getQuestID() }, null, null,
							null);
					if (cursor.moveToNext()) {
						quest.setStatus(cursor.getString(cursor
								.getColumnIndex("status")));
						quest.setDuration(cursor.getString(cursor
								.getColumnIndex("duration")));
					}

					break;
				}
				event = parser.next();
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (db != null) {
				db.close();
			}
		}
		return quest;
	}

}
